<template>
  <t-row :gutter="[24, 24]">
    <t-col :flex="3">
      <div class="user-left-greeting">
        <div>
          Hi, PetLover
          <span class="regular"> {{ $t('pages.user.markDay') }}</span>
        </div>
        <img src="../../../assets/pethome-logo.png" class="logo" />
      </div>

      <t-card class="user-info-list" :title="$t('pages.user.personalInfo.title')" :bordered="false">
        <template #actions>
          <t-button theme="default" shape="square" variant="text" @click="visibleEditMine = true">
            <t-icon name="edit" />
          </t-button>
        </template>
        <t-descriptions :column="4" item-layout="vertical">
          <t-descriptions-item v-for="(item, index) in USER_INFO" :key="index" :label="$t(item.title)">
            {{ item.title === '创建时间' ? item.content.split('T')[0] : $t(item.content) }}
          </t-descriptions-item>
        </t-descriptions>
      </t-card>

      <t-dialog
        v-model:visible="visibleEditMine"
        header="编辑个人信息"
        mode="modeless"
        draggable
        :on-confirm="submitEvaluation"
      ><div>
        <t-form :preventSubmitDefault="false" :showErrorMessage="false"  :rules="FORM_RULES" :data="formData" :colon="true">
          <t-form-item label="昵称" name="name" initial-data="TDesign">
            <t-input v-model="formData.name" placeholder="请输入内容" />
          </t-form-item>
          <t-form-item label="手机号码" name="tel" initial-data="123456">
            <t-input  v-model="formData.tel" placeholder="请输入内容" />
          </t-form-item>
          </t-form>
      </div>
        </t-dialog>
<!--      猜你喜欢功能未实现-->

      <t-card class="content-container" :bordered="false">

<!--        <t-tabs >-->
<!--          <t-tab-panel value="first" :label="$t('pages.user.contentList')">-->
<!--            <p>{{ $t('pages.user.contentList') }}</p>-->
<!--          </t-tab-panel>-->
<!--          <t-tab-panel value="first" :label="$t('pages.user.gylList')">-->
        <div class="Title">{{$t('pages.user.gylList')}}</div>
            <div style="padding-top:18px">
            <dialog-form v-model:visible="formDialogVisible" :data="formData1" />
            <template v-if="pagination.total > 0 && !dataLoading">
              <div class="list-card-items">
                <t-row :gutter="[16, 16]">
                  <t-col v-for="product in productList.slice(
            pagination.pageSize * (pagination.current - 1),
            pagination.pageSize * pagination.current,
          )" :key="product.index" :lg="4" :xs="6" :xl="3">
                    <product-card class="list-card-item" :product="product" />
                  </t-col>
                </t-row>
              </div>
              <div class="list-card-pagination">
                <t-pagination v-model="pagination.current" v-model:page-size="pagination.pageSize" :total="pagination.total"
                              :page-size-options="[12, 24, 36]" @page-size-change="onPageSizeChange" @current-change="onCurrentChange" />
              </div>
            </template>
            <div v-else-if="dataLoading" class="list-card-loading">
              <t-loading size="large" text="加载数据中..." />
            </div>
            </div>
<!--          </t-tab-panel>-->
<!--            <t-card :bordered="false" class="card-padding-no" :title="$t('pages.user.visitData')" describe="（次）">-->
<!--              <template #actions>-->
<!--                <t-date-range-picker-->
<!--                  class="card-date-picker-container"-->
<!--                  :default-value="LAST_7_DAYS"-->
<!--                  theme="primary"-->
<!--                  mode="date"-->
<!--                  @change="onLineChange"-->
<!--                />-->
<!--              </template>-->
<!--              <div id="lineContainer" style="width: 100%; height: 328px" />-->
<!--            </t-card>-->


<!--          <t-tab-panel value="third" :label="$t('pages.user.contentList')">-->
<!--            <p>{{ $t('pages.user.contentList') }}</p>-->
<!--          </t-tab-panel>-->
<!--        </t-tabs>-->
      </t-card>
    </t-col>

    <t-col :flex="1">
      <t-card class="user-intro" :bordered="false">
        <t-avatar size="80px" :image="image"/>
        <div class="name">{{ NAME}}</div>
        <div class="position">{{ $t('pages.user.personalInfo.position') }}</div>
      </t-card>

      <t-card :title="$t('pages.user.order')" class="user-order" :bordered="false">
        <template #actions>
          <t-button theme="default" shape="square" variant="text" @click="orderDetails">
            <t-icon name="list" />
          </t-button>
        </template>
<!--        <template>-->
<!--          <t-space direction="vertical">-->
<!--            <t-radio-group v-model="column" :options="columnOptions"></t-radio-group>-->
<!--        <t-list-item v-for="(item, index) in ORDER_LIST" :key="index" :label="$t(item.title)" >-->
<!--            <t-descriptions bordered :column="column" >-->
<!--              <t-descriptions-item label="订单名称"> {{$t( item.content) }}</t-descriptions-item>-->
<!--            </t-descriptions>-->
<!--&lt;!&ndash;          </t-space>&ndash;&gt;-->
<!--&lt;!&ndash;        </template>&ndash;&gt;-->
<!--&lt;!&ndash;        <t-list :split="false">&ndash;&gt;-->
<!--&lt;!&ndash;           &ndash;&gt;-->
<!--&lt;!&ndash;            <t-list-item-meta :title="item.content" :content="item.content" />&ndash;&gt;-->
<!--          </t-list-item>-->
<!--        </t-list>-->
      </t-card>

      <t-card :title="$t('pages.user.OtherFunction')" class="product-container" :bordered="false">
<!--        <template #actions>-->
<!--          <t-button theme="default" shape="square" variant="text">-->
<!--            <t-icon name="ellipsis" />-->
<!--          </t-button>-->
<!--        </template>-->
        <t-row class="content" :getters="16">
          <t-col v-for="(item, index) in PRODUCT_LIST" :key="index" :span="3" class="icon-container" >
            <t-button v-if="item=='更改密码'" theme="default" variant="text" @click="visibleEditPw = true">
              <edit-icon v-if="item=='更改密码'" class="large-icon"/>
            </t-button>
<t-button v-else theme="default" variant="text" @click="NotifyPlugin.info({ title: '温馨提示', content: '功能开发中，敬请期待！' })">
            <user-vip-icon v-if="item=='申请入会'" class="large-icon"/>
            <service-icon v-if="item=='联系客服'" class="large-icon"/>
            <usergroup-icon v-if="item=='加入我们'" class="large-icon"/>
  </t-button>
          </t-col>
        </t-row>
        <t-row class="content" :getters="16">
          <t-col v-for="(item, index) in PRODUCT_LIST" :key="index" :span="3" class="icon-container">
            {{ item }}
          </t-col>
        </t-row>
      </t-card>

      <t-dialog
        v-model:visible="visibleEditPw"
        header="更改密码"
        mode="modeless"
        draggable
        :on-confirm="pwEvaluation"
      ><div>
        <t-form :preventSubmitDefault="false" :showErrorMessage="false"  :rules="FORM_RULES1" :data="formData" :colon="true">
          <t-form-item label="当前密码" name="currentpasswd" >
            <t-input v-model="formData.currentpasswd" placeholder="请输入当前密码" />
          </t-form-item>
          <t-form-item label="新密码" name="newpasswd" initial-data="000000">
            <t-input  v-model="formData.newpasswd" placeholder="请输入新密码" />
          </t-form-item>
        </t-form>
      </div>
      </t-dialog>
    </t-col>
  </t-row>
</template>
<script lang="ts">
export default {
  name: 'UserIndex',
};
</script>
<script setup lang="ts">
import axios from 'axios';
import { ref, reactive } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { LineChart } from 'echarts/charts';
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import {

  EditIcon,
  HistoryIcon,
  ServiceIcon,
  UsergroupIcon, UserVipIcon
} from 'tdesign-icons-vue-next';
import type { DateRangeValue } from 'tdesign-vue-next';
import { NotifyPlugin } from 'tdesign-vue-next';
import { computed, nextTick, onMounted, onUnmounted, PropType, watch } from 'vue';
import ProductCard, { CardProductType } from '@/components/product-card/index.vue';
import router from '@/router';
import ProductAIcon from '@/assets/assets-product-1.svg';
import ProductBIcon from '@/assets/assets-product-2.svg';
import ProductCIcon from '@/assets/assets-product-3.svg';
import ProductDIcon from '@/assets/assets-product-4.svg';
import { ORDER_LIST } from '@/pages/user/Orders';
import { useSettingStore } from '@/store';
import { changeChartsTheme } from '@/utils/color';
import { LAST_7_DAYS } from '@/utils/date';

import { PRODUCT_LIST, TEAM_MEMBERS, USER_INFO_LIST, UserInfoListType } from '../constants';
import DialogForm from "@/pages/shop/goods/components/DialogForm.vue";


const FORM_RULES = { name: [{ required: true, message: '姓名必填' }] , tel: [{ required: true, message: '手机号码必填' }] };
const FORM_RULES1 = { currentpasswd: [{ required: true, message: '当前密码必填' }] , newpasswd: [{ required: true, message: '新密码必填' }] };
const pagination = ref({ current: 1, pageSize: 8, total: 0 });
const formDialogVisible = ref(true);
const visibleEditPw = ref(false);
const formData = reactive({
  newpasswd: '',
  currentpasswd: '',
  name: '',
  tel: '',
  gender: '',
  course: [],
  status: false,
});
const form = ref(null);
const onReset = () => {
  MessagePlugin.success('重置成功');
};

const formData1 = reactive({
  id:0,
  img: '',
  name: '',
  status: '',
  description: '',
  type: '0',
  mark: '',
  amount: 0,
  });
const toAll = async (queryParams ={}) => {
  try {
    const response = await axios.get("/api/user/getItems",{params:queryParams});

    const list = response.data.data.list;;
    productList.value = list;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
    localStorage.setItem('lastQueryParams', JSON.stringify(queryParams));
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const submitForm = async () => {
  form.value.submit();
  form.value.submit({ showErrorMessage: false });

  // 校验数据，代码有效，勿删
  // form.value.validate();

  // 校验数据：只提交和校验，不在表单中显示错误文本信息。下方代码有效，勿删
  // form.value.validate({ showErrorMessage: false }).then((validateResult) => {
  //   if (validateResult && Object.keys(validateResult).length) {
  //     const firstError = Object.values(validateResult)[0]?.[0]?.message;
  //     MessagePlugin.warning(firstError);
  //   }
  // });
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const resetForm = () => {
  form.value.reset();
  // 下方为示例代码，有效，勿删
  // form.value.reset({ type: 'initial' });
  // form.value.reset({ type: 'empty' });
  // form.value.reset({ type: 'initial', fields: ['name'] });
  // form.value.reset({ type: 'empty', fields: ['name'] });
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const validateOnly = async () => {
  const result = await form.value.validateOnly();
  MessagePlugin.success('打开控制台查看校验结果');
  console.log('validateOnly', result);
};





echarts.use([GridComponent, TooltipComponent, LineChart, CanvasRenderer, LegendComponent]);

let lineContainer: HTMLElement;
let lineChart: echarts.ECharts;
const productList = ref([]);
const dataLoading = ref(true);
const USER_INFO = ref<UserInfoListType[]>([]);
const NAME = ref('');
const store = useSettingStore();
const chartColors = computed(() => store.chartColors);
const submitEvaluation = async () => {
  try {
    const response = await axios.post('/api/user/editUserInfo', {
      username: formData.name,
      number: formData.tel,
    });
    const result = response.data;
    if (result.success) {
      NotifyPlugin.success({
        title: '成功',
        content: '个人信息编辑成功',
        duration: 3000,
      });
      visibleEditMine.value = false;
      USER_INFO.value = [];
      await getSelfInfo();
    } else {
      NotifyPlugin.error({
        content: '编辑失败，请重试'
      });
    }
  } catch (error) {
    console.log(error);
    NotifyPlugin.error({
      content: '请求失败，请稍后重试',
    });
  }
};
const pwEvaluation = async () => {
  try {
    const response = await axios.post('/api/user/editPasswd', {
      currentpasswd: formData.currentpasswd,
      newpasswd: formData.newpasswd,
    });
    const result = response.data;
    if (result.success) {
      NotifyPlugin.success({
        title: '成功',
        content: '更改密码成功，请重新登录',
        duration: 3000,
      });
      await router.push('/login');
    } else {
      NotifyPlugin.error({
        content: '更改失败，请检查当前密码是否正确，如确认无误，请重试'
      });
    }
  } catch (error) {
    console.log(error);
    NotifyPlugin.error({
      content: '请求失败，请稍后重试',
    });
  }
};

const onPageSizeChange = (size: number) => {
  pagination.value.pageSize = size;
  pagination.value.current = 1;
};
const onCurrentChange = (current: number) => {
  pagination.value.current = current;
};


const getSelfInfo = async () => {
  try {
    const response: { data: { success: boolean; data: { id: string; number: string;name: string; isVIP: boolean; createat:string } } } =
      await axios.get('/api/user/getSelfInfo');
    console.info(response);
    if (response.data.success === true) {
      const info = response.data.data;
      USER_INFO.value.push({
        title: '电话号码',
        content: String(info.number),
      });
      USER_INFO.value.push({
        title: '是否是VIP',
        content: info.isVIP ? '是' : '否',
      });
      USER_INFO.value.push({
        title: '创建时间',
        content: String(info.createat),
      });
      USER_INFO.value.push({
        title: 'ID',
        content: String(info.id),
      });
      NAME.value = info.name;

      console.info(USER_INFO.value);
    } else {
      NotifyPlugin.error({
        content: '未读到个人信息',
      });
    }
  } catch (error) {
    console.log(error);
  }
};
const updateContainer = () => {
  lineChart?.resize({
    width: lineContainer.clientWidth,
    height: lineContainer.clientHeight,
  });
};

onMounted(() => {
  getSelfInfo();
  window.addEventListener('resize', updateContainer, false);

  // 获取存储的查询参数
  const lastQueryParams = JSON.parse(localStorage.getItem('lastQueryParams') || '{}');
  toAll(lastQueryParams);

});
const orderDetails = () => {
  router.push('/user/order');
  console.log('Order details button clicked');
};

onUnmounted(() => {
  window.removeEventListener('resize', updateContainer);
});
const image = 'https://tdesign.gtimg.com/site/avatar.jpg';

const visibleEditMine = ref(false);

const getIcon = (type: string) => {
  switch (type) {
    case '浏览记录':
      return ProductCIcon;
    case '联系客服':
      return ProductCIcon;
    case 'c':
      return ProductCIcon;
    case 'd':
      return ProductDIcon;
    default:
      return ProductAIcon;
  }
};




const columnOptions = [2, 3, 4];

const column = ref(2);
watch(
  () => store.brandTheme,
  () => {
    changeChartsTheme([lineChart]);
  },
);
const props = defineProps({
  product: {
    type: Object as PropType<CardProductType>,
  },
});
</script>

<style lang="less" scoped>

@import '../index.less';
.Title{
  font-size: 20px;
  color: var(--td-text-color-primary);
    word-break: break-all;
  }
.icon-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.large-icon {
  font-size: 2em; /* Adjust the size as needed */
}
.t-descriptions {
  margin-top: 24px;
}
</style>
